let root = [3, 9, 20, null, null, 15, 7]
function TreeNode(val, left, right) {
    this.val = (val === undefined ? 0 : val);
    this.left = (left === undefined ? null : left);
    this.right = (right === undefined ? null : right);
}

// 将数组转换为二叉树
function arrayToTree(arr) {
    if (arr.length === 0 || arr[0] === null) return null;

    const root = new TreeNode(arr[0]);
    const queue = [root];
    let i = 1;

    while (queue.length > 0 && i < arr.length) {
        const current = queue.shift();

        // 处理左子节点
        if (i < arr.length && arr[i] !== null) {
            current.left = new TreeNode(arr[i]);
            queue.push(current.left);
        }
        i++;

        // 处理右子节点
        if (i < arr.length && arr[i] !== null) {
            current.right = new TreeNode(arr[i]);
            queue.push(current.right);
        }
        i++;
    }

    return root;
}

var zigzagLevelOrder = function (root) {
    if (root === null) return [];

    const res = [];
    const queue = [root];
    let k = 1; // 层数计数器

    while (queue.length > 0) {
        const levelSize = queue.length;
        const currentLevel = [];

        for (let i = 0; i < levelSize; i++) {
            const current = queue.shift();
            currentLevel.push(current.val);

            // 始终按从左到右的顺序入队子节点
            if (current.left) queue.push(current.left);
            if (current.right) queue.push(current.right);
        }

        // 只有在偶数层时反转当前层的结果
        if (k % 2 === 0) {
            currentLevel.reverse();
        }

        res.push(currentLevel);
        k++;
    }

    return res;
};

// 转换数组为二叉树
const treeRoot = arrayToTree(root);
console.log(zigzagLevelOrder(treeRoot)); 